package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.auth.model.po.Company;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.feignclient.auth.CompanyClient;
import com.xuecheng.content.mapper.CourseBaseMapper;
import com.xuecheng.content.model.dto.CourseReqDto;
import com.xuecheng.content.model.dto.CourseBaseInfoDto;
import com.xuecheng.content.model.dto.QueryCourseDetailDto;
import com.xuecheng.content.model.dto.QueryCourseParamsDto;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class CourseBaseInfoServiceImpl extends ServiceImpl<CourseBaseMapper, CourseBase>
    implements CourseBaseInfoService {
    @Autowired
    CompanyClient companyClient;

    @Autowired
    CourseMarketService courseMarketService;

    @Autowired
    CourseCategoryService courseCategoryService;

    @Autowired
    CoursePublishService coursePublishService;

    @Autowired
    CourseTeacherService courseTeacherService;

    @Autowired
    TeachplanMediaService teachplanMediaService;

    @Autowired
    TeachplanService teachplanService;

    /**
     * 分页查询课程基本信息
     * @param pageParams
     * @param dto
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,
            PageParams pageParams, QueryCourseParamsDto dto) {
        Page<CourseBase> courseBasePage = new Page<>(pageParams.getPageNo(),pageParams.getPageSize());
        LambdaQueryWrapper<CourseBase> wrapper = new LambdaQueryWrapper<>();
        if(dto != null){
            wrapper.like(!StringUtils.isBlank(dto.getCourseName()),CourseBase::getName,
                    dto.getCourseName());
            wrapper.eq(!StringUtils.isBlank(dto.getAuditStatus()),CourseBase::getAuditStatus,
                    dto.getAuditStatus());
            wrapper.eq(!StringUtils.isBlank(dto.getPublishStatus()),CourseBase::getStatus,
                    dto.getPublishStatus());
        }
        wrapper.eq(companyId != null,CourseBase::getCompanyId,companyId);
        page(courseBasePage,wrapper);
        return new PageResult<>(courseBasePage.getRecords(),pageParams.getPageNo(),
                pageParams.getPageSize(),courseBasePage.getTotal());
    }

    /**
     * 添加课程信息
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto addCourse(Long companyId, CourseReqDto dto) {
        //合法性校验
        if (StringUtils.isBlank(dto.getName())) {
            throw new RuntimeException("课程名称为空");
        }

        if (StringUtils.isBlank(dto.getMt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            throw new RuntimeException("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            throw new RuntimeException("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            throw new RuntimeException("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            throw new RuntimeException("收费规则为空");
        }
        //然后将传入的课程信息分别添加到课程基本信息表和课程营销表
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(dto,courseBase);
        //然后设置没有复制过来的字段
        courseBase.setCompanyId(companyId);
        //然后调用远程接口，根据机构companyId查询机构名称
        Company company = companyClient.getById(companyId.toString());
        //然后设置没有拷贝过来的属性
        courseBase.setCompanyName(company.getName());
        courseBase.setAuditStatus("202002");
        courseBase.setStatus("203001");
        this.save(courseBase);
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto,courseMarket);
        courseMarket.setId(courseBase.getId());
        saveCourseMarket(courseMarket);
        return getCourseBaseInfoDtoById(courseBase.getId());
    }

    public CourseBaseInfoDto getCourseBaseInfoDtoById(Long courseId) {
        CourseBase courseBase = getById(courseId);
        if(courseBase == null) return null;
        CourseBaseInfoDto dto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,dto);
        CourseMarket courseMarket = courseMarketService.getById(courseId);
        if(courseMarket != null){
            BeanUtils.copyProperties(courseMarket,dto);
        }
        CourseCategory mt = courseCategoryService.getById(courseBase.getMt());
        CourseCategory st = courseCategoryService.getById(courseBase.getSt());
        dto.setMtName(mt.getName());
        dto.setStName(st.getName());
        return dto;
    }

    public int saveCourseMarket(CourseMarket courseMarket){
        if(StringUtils.isEmpty(courseMarket.getCharge())){
            throw new RuntimeException("收费规则为空");
        }
        if(courseMarket.getCharge().equals("201001")){
            if(courseMarket.getPrice() == null ||
                    courseMarket.getPrice().floatValue() <= 0 ||
                    courseMarket.getOriginalPrice().floatValue() <= 0){
                XueChengPlusException.cast("课程的价格不能为空且必须大于0");
            }
        }
        CourseMarket market = courseMarketService.getById(courseMarket.getId());
        if(market == null){
            courseMarketService.save(courseMarket);
        }else{
            courseMarketService.updateById(courseMarket);
        }
        return 1;
    }

    /**
     * 更新课程信息
     * @param companyId
     * @param dto
     * @return
     */
    @Override
    public CourseBaseInfoDto updateCourse(Long companyId, CourseReqDto dto) {
        if(dto == null || dto.getId() == null){
            XueChengPlusException.cast("更新时要传入课程信息");
        }
        CourseBase courseBase = getById(dto.getId());
        if(courseBase == null){
            XueChengPlusException.cast("当前课程不存在");
        }
        if(courseBase.getCompanyId() != null &&
                !courseBase.getCompanyId().equals(companyId)){
            XueChengPlusException.cast("当前课程不属于本机构，无权操作");
        }
        BeanUtils.copyProperties(dto,courseBase);
        updateById(courseBase);
        CourseMarket courseMarket = courseMarketService.getById(dto.getId());
        CourseMarket market = new CourseMarket();
        BeanUtils.copyProperties(dto,market);
        if(courseMarket == null){
            courseMarketService.save(market);
        }else{
            courseMarketService.updateById(market);
        }
        return getCourseBaseInfoDtoById(dto.getId());
    }

    /**
     * 删除课程
     * @param companyId
     * @param id
     */
    @Transactional
    @Override
    public void deleteCourse(Long companyId, Long id) {
        CourseBase courseBase = getById(id);
        if(courseBase == null){
            XueChengPlusException.cast("当前课程不存在");
        }
        if(courseBase.getCompanyId() != null &&
                !companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast("当前课程不属于本机构，无权操作");
        }
        //课程删除时，要删除课程基本信息表、课程营销表、课程计划表、
        //课程计划与视频关联表、课程教师关联表
        //删除之前要判断当前课程是否发布，如果发布就不能删除，要先下架才能删除
        CoursePublish coursePublish = coursePublishService.getById(id);
        if(coursePublish != null){
            XueChengPlusException.cast("当前课程处于发布状态，请先下架再删除");
        }
        //删除课程教师关联表信息
        courseTeacherService.remove(new LambdaQueryWrapper<CourseTeacher>()
                .eq(CourseTeacher::getCourseId,id));
        //删除课程计划与视频关联表信息
        teachplanMediaService.remove(new LambdaQueryWrapper<TeachplanMedia>()
                .eq(TeachplanMedia::getCourseId,id));
        //删除课程计划表信息
        teachplanService.remove(new LambdaQueryWrapper<Teachplan>()
                .eq(Teachplan::getCourseId,id));
        //删除课程营销表信息
        courseMarketService.removeById(id);
        //删除课程基本信息表信息
        removeById(id);
    }

    /**
     * 根据条件查询课程基本信息
     * @param dto
     * @return
     */
    @Override
    public CourseBase getCourseBase(QueryCourseDetailDto dto) {
        return getOne(new LambdaQueryWrapper<CourseBase>()
                .eq(dto.getId() != null,CourseBase::getId,dto.getId())
                .eq(dto.getCompanyId() != null,CourseBase::getCompanyId,dto.getCompanyId())
                .eq(StringUtils.isNotBlank(dto.getMt()),CourseBase::getMt,dto.getMt())
                .eq(StringUtils.isNotBlank(dto.getSt()),CourseBase::getSt,dto.getSt())
                .eq(StringUtils.isNotBlank(dto.getGrade()),CourseBase::getGrade,dto.getGrade())
                .eq(StringUtils.isNotBlank(dto.getTeachmode()),CourseBase::getTeachmode,dto.getTeachmode())
                .eq(StringUtils.isNotBlank(dto.getPic()),CourseBase::getPic,dto.getPic())
                .eq(StringUtils.isNotBlank(dto.getAuditStatus()),CourseBase::getAuditStatus,dto.getAuditStatus())
                .eq(StringUtils.isNotBlank(dto.getStatus()),CourseBase::getStatus,dto.getStatus())
                .like(StringUtils.isNotBlank(dto.getCompanyName()),CourseBase::getCompanyName,dto.getCompanyName())
                .like(StringUtils.isNotBlank(dto.getName()),CourseBase::getName,dto.getName())
                .like(StringUtils.isNotBlank(dto.getUsers()),CourseBase::getUsers,dto.getUsers())
                .like(StringUtils.isNotBlank(dto.getTags()),CourseBase::getTags,dto.getTags()));
    }
}









